package com.woniuxy.shop.Controller;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hc.entity.*;
import com.woniuxy.shop.Entity.ChartData;
import com.woniuxy.shop.Entity.ResponseEntity;
import com.woniuxy.shop.Service.LLService;
import com.woniuxy.shop.feignclient.ProviderServerfeignClient;
import com.woniuxy.shop.feignclient.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName LLcontroller
 * @Description
 * @Author ll
 * @Date 2022/10/19 15:43
 * @Version 1.0
 **/
@Transactional
@RestController
@CrossOrigin
@RequestMapping("/test")
public class LLcontroller {
    @Autowired
    LLService llService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ProviderServerfeignClient providerServerfeignClient;
    @Resource
    private UserFeignClient userFeignClient;
    @RequestMapping("/isexitshop")
    ResponseEntity isexitshop(@RequestParam("id") int id){
        ResponseEntity result = new ResponseEntity<>();
        boolean isexitshop = llService.isexitshop(id);
        result.setData(isexitshop);
        //返回值为true则该用户没有店铺
        return result;
    }

    @RequestMapping("/ispass")
    ResponseEntity ispass(@RequestParam("id") int id){
        ResponseEntity result = new ResponseEntity<>();
        boolean isexitshop = llService.ispass(id);
        result.setData(isexitshop);
        //返回值为true则该用户没有店铺
        return result;
    }
    @RequestMapping("/insertshop")
    ResponseEntity addshop(@RequestBody Shop shop){
        //后期修改从jwt中获取用户id
        shop.setUserId(1);
        llService.insertshop(shop);
        return new ResponseEntity<>("200","成功","");
    }
    @RequestMapping("/insertgoods")
    ResponseEntity addgoods(@RequestBody Goods goods){
        //后期修改从jwt中获取用户id
        //然后根据用户id查询店铺id
        goods.setShopId(5);
        llService.insertgoods(goods);
        return new ResponseEntity<>("200","成功","");

    }
    @RequestMapping("/getmygoods")
    ResponseEntity<List<Goods>> getmygoods(){
        //后续从jwt中获取店主ID
        List<Goods> getmygoods = llService.getmygoods(1);
        ResponseEntity<List<Goods>> result = new ResponseEntity<>();
        result.setData(getmygoods);
        result.setCode("200");
        result.setMsg("成功");
        return result;
    }
    @RequestMapping("/getgoodsdetail")
    ResponseEntity<Goods> getgoodsdetail(@RequestParam("id") int id){
        Goods goods = getGoodsdetail(id);
        if(goods!=null){
            ResponseEntity<Goods> result = new ResponseEntity<>();
            result.setData(goods);
            result.setMsg("成功");
            result.setCode("200");
            return result;
        }else{
            ResponseEntity<Goods> result = new ResponseEntity<>();
            result.setData(goods);
            result.setMsg("商品不存在");
            result.setCode("369");
            return result;
        }

    }
    private Goods getGoodsdetail(int id) {
        String key = "goodsdetail" + id;
        //查询缓存
        String goods = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(goods)) {
            //缓存存在，直接将缓存返回
            Goods goods1 = JSONUtil.toBean(goods, Goods.class);
            return goods1;
        }
        //判断缓存是否是空值
        if (goods != null) {
            return null;
        }
        //实现缓存重建
        //先申请锁
        String key2 = "trycatchgoodsdetail" + id;
        Goods getgoodsdetail;
        try {
            boolean trychatch = trychatch(key2);
            if (!trychatch) {
                Thread.sleep(50);
                return getGoodsdetail(id);
            }
            //不存在，就从数据库查询
            getgoodsdetail = llService.getgoodsdetail(id);
            //模拟延时
            Thread.sleep(200);
            //再写入缓存
            if (getgoodsdetail == null) {
                //防止缓存穿透，如果查询出来是空值则将空值写入缓存
                stringRedisTemplate.opsForValue().set(key, "", 2L, TimeUnit.MINUTES);
                return null;
            }
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(getgoodsdetail), 30L, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(key2);
        }
        return getgoodsdetail;
    }
    private boolean trychatch(String key){
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }
    @RequestMapping("/changestock")
    ResponseEntity changestock(@RequestBody Goods goods){
        llService.changestock(goods.getId(),goods.getStock()+goods.getShopId());
//        //   增加库存时同时在redis内增加一个添加库存的缓存,设置过期时间
//        String key=goods.getId()+"商品到货";
//        long timeout = 60*60*10;
//        // 通过定时扫描redis数据来判断是否需要发送短信给对应用户
//        stringRedisTemplate.opsForValue().set(key,"1",timeout, TimeUnit.SECONDS);
        NoticeArriva noticeArriva =new NoticeArriva();
        Goods goods1 = new Goods();
        goods1.setId(goods.getId());
        noticeArriva.setGoods(goods1);
        com.hc.utils.ResponseEntity responseEntity = userFeignClient.selectGoodNotice(noticeArriva);
        Object data =responseEntity.getData();
        if(data != null){  //有设置到货通知的用户
            List<NoticeArriva> list = (List<NoticeArriva>) data;
            for (int i = 0; i < list.size(); i++) {
                //调用消息生产者，发送一个消息到消息队列:通过消息队列来将短信发送到用户手机上。
                providerServerfeignClient.hasGoodsNotice(list.get(i));
            }

        }


        ResponseEntity result=new ResponseEntity<>("200","成功","");
        return result;

    }
    @RequestMapping("/offtheshelf")
    @Transactional
    ResponseEntity offtheshelf(@RequestParam("id") int id){
        //先更新数据库
        llService.offyheshelf(id);
        String key = "goodsdetail"+id;
        //在删除缓存
        stringRedisTemplate.delete(key);
        ResponseEntity result=new ResponseEntity<>("200","成功","");
        return result;
    }
    @RequestMapping("/finish")
    ResponseEntity<List<Order>> finish(){
        //后续从jwt中获取id
        List<Order> finish = llService.finish(5);
        ResponseEntity<List<Order>> result=new ResponseEntity<>();
        result.setData(finish);
        result.setMsg("成功");
        result.setCode("200");
        return result;


    }
    @RequestMapping("/allorder")
    ResponseEntity<List<Order>> allorder(){
//        后续从jwt中获取id
        List<Order> finish = llService.allorder(5);
        ResponseEntity<List<Order>> result=new ResponseEntity<>();
        result.setData(finish);
        result.setMsg("成功");
        result.setCode("200");
        return result;

    }

    @RequestMapping("/notfinish")
    ResponseEntity<List<Order>> notfinish(){
        //后续从jwt中获取id
        List<Order> finish = llService.notfinish(5);
        ResponseEntity<List<Order>> result=new ResponseEntity<>();
        result.setData(finish);
        result.setMsg("成功");
        result.setCode("200");
        return result;
    }
    @RequestMapping("/addsecondkill")
    ResponseEntity addsecondkill(@RequestBody Seckill seckill){
        //后续从jwt中获取shopid
        seckill.setShopId(5);
        llService.addsecondkill(seckill);
        ResponseEntity result=new ResponseEntity<>("200","成功","");
        return result;
    }

    @RequestMapping("/addDiscountType")
    ResponseEntity addDiscountType(@RequestBody DiscountType discountType){
        //后续从jwt中获取shopid
        int goodsid = discountType.getShopId();
        discountType.setShopId(5);
        llService.addDiscountType(discountType,goodsid);
        ResponseEntity result=new ResponseEntity<>("200","成功","");
        return result;
    }
    @RequestMapping("/closeshop")
    ResponseEntity closeshop(){
        //从JWT中获取id
        llService.dayang(5);
        ResponseEntity result=new ResponseEntity<>("200","成功","");
        return result;
    }

    @RequestMapping("/openshop")
    ResponseEntity openshop(){
        //从JWT中获取id
        llService.openshop(5);
        ResponseEntity result=new ResponseEntity<>("200","成功","");
        return result;
    }
    @RequestMapping("/getshopstatus")
    ResponseEntity getshopstatus(){
        //JWT获取用户id
        Shop getshopstatus = llService.getshopstatus(1);
        if(getshopstatus.getStatus().equals("n")){
            ResponseEntity result=new ResponseEntity<>("202","成功","");
            return result;
        }else{
            ResponseEntity result=new ResponseEntity<>("201","成功","");
            return result;
        }
    }

    @RequestMapping("/getChartData")
    ResponseEntity<ChartData> getChartData() throws ParseException {
        //jwt中获取id，shopid
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = new Date();
        String today = format.format(date);
        ChartData chartData = llService.getChartData(today, 5);
        ResponseEntity<ChartData> result = new ResponseEntity<>();
        result.setData(chartData);
        result.setCode("200");
        result.setMsg("成功");
        return result;
    }
    @RequestMapping("/today")
    ResponseEntity today() throws ParseException {
        //jwt中获取id，shopid
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = new Date();
        String today = format.format(date);
        BigDecimal today1 = llService.today(today, 5);
        ResponseEntity result=new ResponseEntity<>();
        result.setData(today1);
        result.setCode("200");
        result.setMsg("成功");
        return result;
    }

    @RequestMapping("/getmonth")
    ResponseEntity getmonth() throws ParseException {
        //jwt中获取id，shopid
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = new Date();
        String today = format.format(date);
        BigDecimal today1 = llService.month(today, 5);
        ResponseEntity result=new ResponseEntity<>();
        result.setData(today1);
        result.setCode("200");
        result.setMsg("成功");
        return result;
    }
    @RequestMapping("/getorder")
    ResponseEntity getorder(@RequestParam("id") int id){
        Order getorder = llService.getorder(id);
        ResponseEntity result=new ResponseEntity<>();
        result.setData(getorder);
        if(getorder.getStatus().equals("p")){
            result.setCode("200");
        }
        if(getorder.getStatus().equals("d")){
            result.setCode("201");
        }
        result.setMsg("成功");
        return result;
    }
    @RequestMapping("/checkorder")
    ResponseEntity checkorder(@RequestParam("id") int id){
        llService.checkorder(id);
        ResponseEntity result=new ResponseEntity<>();
        result.setCode("200");
        return result;
    }


    @RequestMapping("/secondkill")
    ResponseEntity secondkill(@RequestParam("id") int id){
        ResponseEntity secondkill = llService.secondkill(id);
        return secondkill;
    }
}